package com.csx.governance.traffic.adapter.outbound;

import com.csx.governance.traffic.route.Filter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.context.support.ApplicationObjectSupport;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;

/**
 * <p> 服务实例提供器的后置处理器 - Spring Cloud LoadBalancer的实现 </p>
 * <p> 主要负责将原生的LoadBalancer的{@link ServiceInstanceListSupplier}替换为自定义的{@link TrafficServiceInstanceSupplier}(内置了全链路灰度的服务实例过滤逻辑)</p>
 * @author cuisongxu
 * @date 2023/3/18 19:49
 */
public class LoadBalancerInstanceSupplierBeanPostProcessor extends ApplicationObjectSupport implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof ServiceInstanceListSupplier) {
            Collection<Filter> values = BeanFactoryUtils.beansOfTypeIncludingAncestors(obtainApplicationContext(), Filter.class).values();
            List<Filter> filters = new ArrayList<>(values);
            filters.sort(Comparator.comparing(Filter::getOrder));
            return new TrafficServiceInstanceSupplier((ServiceInstanceListSupplier) bean, filters);
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
